import { Component, OnInit, Input, ContentChild, TemplateRef, EventEmitter, Output, Injector } from '@angular/core';

import { InitService } from 'app/public/serve/init/init.service';
@Component({
  selector: 'zs-step',
  templateUrl: './step.component.html',
  styleUrls: ['./step.component.css']
})
export class StepComponent implements OnInit {
  // public injector:Injector
  public initService: InitService
  constructor(
    injector:Injector
  ) { 
    this.initService = injector.get(InitService)
  }

  @Input() steps = [
    {
      title: '第一步'
    }, {
      title: '第二步'
    }, {
      title: '第三步'
    }, {
      title: '第四步'
    }, {
      title: '第五步'
    }, {
      title: '第六步'
    }
  ];
  @Input() modalId: string;
  @Input() modalTitle:string = "默认标题-默认";
  rate: number;
  _step: number;
  @Output() stepChange: EventEmitter<number> = new EventEmitter<number>();
  @Output() clickStep:EventEmitter<number|string> = new EventEmitter();
  @Output() close = new EventEmitter<any>();
  @ContentChild('tmpl') tmpl: TemplateRef<any>;
  ngOnInit() {
    this.step = 1;
    //console.log(this.modalId)
    if (!this.modalId) {
      throw ("你需要传入一个modalId")
    }
  }
  getLeft(i: number) {
    if (this.steps.length) {
      let length = Math.floor(100 / (this.steps.length - 1))
      length *= i
      return `calc(${length}% - 25px)`
    }
  }
  previous() {
    --this.step;
  }
  next() {
    ++this.step
  }
  stepTo(step: number) {
    this.clickStep.emit(step)
    // this.step = step
  }
  isActive(step: number) {
    return this._step >= (step + 1)
  }
  private stepToRate(step: number = this._step) {
    let length = this.steps.length;
    if (step > 0 && step <= length) {
      let rate = Math.floor(100 / (length - 1));
      let result = (step - 1) * rate
      return result
    } else {
      //console.trace("step 不可以<0 或者 > 数组steps的长度")
      throw ("step 不可以<0 或者 > 数组steps的长度");
    }
  }
  @Input() set step(value: number) {
    let length = this.steps.length;
    if (!length) {
      return
    }
    if (value > 0 && value <= length) {
      this._step = value;
      this.rate = this.stepToRate();
      this.stepChange.emit(+value)
    } else {
      // console.trace("step 不可以<0 或者 > 数组steps的长度")
      if (value <= 0) {
        this._step = 1;
        this.rate = this.stepToRate();
        this.stepChange.emit(1)
      }
      if(value > length){
        this._step = length;
        this.rate = this.stepToRate();
        this.stepChange.emit(length)
      } 
      //console.error("step 不可以<0 或者 > 数组steps的长度");
    }
  }
  get step() {
    return this._step;
  }
  _close(){
    this.close.emit()
  }
}
